import win32gui
import win32con
import time
import pyautogui
import pygetwindow as gw
import cv2
import numpy as np


def activate_and_maximize_wecom():
    # 获取企业微信窗口句柄
    hwnd = win32gui.FindWindow(None, "企业微信")
    if hwnd == 0:
        print("未找到企业微信窗口，请确保企业微信已打开。")
        return None
    # 激活窗口
    win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
    win32gui.SetForegroundWindow(hwnd)
    # 最大化窗口
    win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
    print("企业微信窗口已激活并最大化。")
    time.sleep(2)
    return hwnd


def search_and_send_message(message):
    # 唤起全局搜索框，假设快捷键是 Ctrl + F
    pyautogui.hotkey('ctrl','alt','f')
    time.sleep(1)
    # 输入“文件助手”
    pyautogui.typewrite("文件助手")
    time.sleep(1)
    # 选中搜索结果
    pyautogui.press('enter')
    time.sleep(5)
    # 发送消息
    pyautogui.typewrite(message)
    pyautogui.press('enter')
    time.sleep(1)


def find_and_click_icon(template_path):
    try:
        # 找到企业微信窗口
        wecom_window = gw.getWindowsWithTitle('企业微信')[0]
        # 截取企业微信窗口截图
        screenshot = pyautogui.screenshot(
            region=(wecom_window.left, wecom_window.top, wecom_window.width, wecom_window.height))
        screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        # 读取模板图标
        template = cv2.imread(template_path, cv2.IMREAD_COLOR)
        h, w = template.shape[:2]
        # 模板匹配
        result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        top_left = max_loc
        center_x = wecom_window.left + top_left[0] + w // 2
        center_y = wecom_window.top + top_left[1] + h // 2
        # 移动鼠标到图标中心并点击
        pyautogui.moveTo(center_x, center_y)
        pyautogui.click()
        time.sleep(1)
    except IndexError:
        print("未找到企业微信窗口，请检查。")
    except cv2.error:
        print("模板匹配出错，请检查模板文件路径。")


def send_file(file_path, template_path):
    find_and_click_icon(template_path)
    # 输入文件路径
    pyautogui.typewrite(file_path)
    time.sleep(1)
    # 按 Enter 键确认发送文件
    pyautogui.press('enter')
    time.sleep(2)
    print("文件发送成功！")


if __name__ == "__main__":
    activate_and_maximize_wecom()
    message = "这是要发送的消息"
    file_path = "D:/adb84106939bc6b4292ebcd1030a6cb12411955.xlsx"
    template_path = "img.png"  # 请替换为实际的模板图标文件路径
    search_and_send_message(message)
    send_file(file_path, template_path)


